package com.tc.activiti.listener;

import cn.hutool.core.collection.CollUtil;
import com.tc.activiti.util.AppUtil;
import com.tc.biz.entity.SysUser;
import com.tc.biz.service.impl.UserServiceImpl;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * @author zengqingfa
 * @date 2019/11/8 13:52
 * @description
 * @email zengqingfa_java@163.com
 * </p>
 * 管养单位负责人监听器
 */
@Component
public class PipeDepartmentManagerTaskListener implements TaskListener {
    //管养单位负责人角色
    public static final String ROLE_KEY_PIPE_DEPARTMENTMANAGER = "pipeManager";

    /**
     * 获取管养单位负责人
     *
     * @param delegateTask
     */
    @Override
    public void notify(DelegateTask delegateTask) {
        //listener不属于spring管理，无法直接注入service,通过AppUtil获取注入的服务
        UserServiceImpl userService = AppUtil.getBean(UserServiceImpl.class);
//        RuntimeService runtimeService = AppUtil.getBean(RuntimeService.class);
//        RepositoryService repositoryService = AppUtil.getBean(RepositoryService.class);
        List<SysUser> userList = userService.findUserByRoleKey(ROLE_KEY_PIPE_DEPARTMENTMANAGER);
        if (CollUtil.isNotEmpty(userList)) {
            for (SysUser sysUser : userList) {
                //设置候选人
                delegateTask.addCandidateUser(sysUser.getUserId().toString());
            }
        }
    }


    public void getBpmnModelDetail() {
        RepositoryService repositoryService = AppUtil.getBean(RepositoryService.class);
        BpmnModel bpmnModel = repositoryService.getBpmnModel("pipeMaintainence2:1:cf617366-0780-11ea-b874-e0d55e40e4f2");
        //process中包含所有的节点信息,包括流程线
        Process process = bpmnModel.getProcessById("x");
        //获取第一个节点信息
        Collection<FlowElement> flowElements = process.getFlowElements();
        List<UserTask> userTaskList = new ArrayList<>();
        //筛选流程中所有的UserTask任务节点
        for (FlowElement flowElement : flowElements) {
            if (flowElement instanceof UserTask) {
                UserTask userTask = ((UserTask) flowElement);
                String assignee = userTask.getAssignee();
                userTaskList.add(userTask);
            }
        }
    }

}
